package at.ac.tuwien.isis.infret;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

import at.ac.tuwien.isis.infret.helper.DocumentIterationContainer;

public class CorpusReader {
	private File dir;
	
	public CorpusReader(String directory){
		dir = new File(directory);
		//System.out.println(dir.list()[0]);
		
	}
	
	public File getDir() {
		return dir;
	}
	
	public Iterator<String> getClassIter(){
		LinkedList<String> classes = new LinkedList<String>();
		String[] list = dir.list(new SVNFilter());
		for (int i = 0; i < list.length; i++)	
			classes.add(list[i]);
		return classes.iterator();
	}
	
	public Iterator<DocumentIterationContainer> getDocIter()
	{
		LinkedList<DocumentIterationContainer> docList = new LinkedList<DocumentIterationContainer>();
		//Get directories -> classes
		File[] dirList = dir.listFiles(new SVNFilter());		
		for(int i = 0; i < dirList.length; i++)
		{
			//System.out.println(dirList[i].getName());
			docList.addAll(iterateDocuments(dirList[i]));
		}
		return getDocIter(dir);
	}
	
	public Iterator<DocumentIterationContainer> getDocIter(File classnames)
	{	 
		return iterateDocuments(classnames).iterator();
	}
	
	public LinkedList<DocumentIterationContainer> iterateDocuments(File path)
	{
		//Get Document Files
		File[] documentList = path.listFiles(new SVNFilter());
		LinkedList<DocumentIterationContainer> docList = new LinkedList<DocumentIterationContainer>();
		
		for (int j =0 ; j < documentList.length; j++)
		{
			DocumentIterationContainer dic = new DocumentIterationContainer(documentList[j].toString(), "");
			//System.out.println(documentList[j].getName());
			
			//Read content of each document
			StringBuffer docData = new StringBuffer(1000);
			try {
				BufferedReader reader = new BufferedReader(
						new FileReader(documentList[j]));
				
		        char[] buf = new char[1024];
		        int numRead=0;
		        while((numRead=reader.read(buf)) != -1){
		            docData.append(buf, 0, numRead);
		        }
		        reader.close();
			} catch (IOException e) {
				//System.err.println("error reading from Document");
				break;
				
			}
			//add String content of Document to Collection
			//System.out.println(docData.toString().trim());
			dic.setDocumentData(docData.toString().trim());
			docList.add(dic);
		}
		return docList;
	}
}
